const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const StylelintPlugin = require('stylelint-webpack-plugin');
const WebpackBar = require('webpackbar');
const production = process.env.NODE_ENV === 'production';

const config = {
  mode: production ? 'production' : 'development',
  entry: path.resolve(__dirname, 'src', 'index.tsx'),
  output: {
    filename: 'static/js/[name].[hash:8].js',
    chunkFilename: 'static/js/[name].chunk.[hash:8].js',
    path: path.resolve(__dirname, 'dist'),
  },
  stats: 'errors-warnings',
  optimization: {
    splitChunks: {
      chunks: 'all',
      name: false,
      maxSize: 200000,
      automaticNameDelimiter: '.'
    }
  },
  devtool: 'source-map',
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.json', 'less'],
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  module: {
    rules: [
      {
        test: /\.(ts|js)(x?)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                '@babel/preset-env',
                '@babel/preset-react',
                '@babel/preset-typescript'
              ],
              plugins: [
                [
                  'import',
                  {
                    libraryName: 'antd',
                    libraryDirectory: 'es',
                    style: true
                  }
                ]
              ]
            }
          },
          'ts-loader'
        ],
      },
      {
        test: /\.(css|less)$/,
        exclude:/node_modules/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options:{
              modules:true,
              esModule: true
            }
          },
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true,
              }
            }
          }
        ]
      },
      {
        test: /\.(css|less)$/,
        include:/node_modules/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                // modifyVars: {
                //     '@primary-color': '#1DA57A'
                // },
                javascriptEnabled: true,
              }
            }
          },
        ]
      },
      {
        test: /\.(png|jpg|gif)$/i,
        use: ['url-loader'],
      },
      {
        enforce: 'pre',
        test: /\.(ts|js)(x?)$/,
        exclude: /node_modules/,
        use: [
          'source-map-loader',
          {
            loader: 'eslint-loader',
            options: {
              emitError: true,
              emitWarning: true,
              failOnError: true,
              failOnWarning: true,
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, 'dist')]
    }),
    new HtmlWebpackPlugin({
      title: '知雀',
      template: path.resolve(__dirname, 'public', 'index.html'),
      templateParameters: {
        title: '知雀'
      },
    }),
    new WebpackBar({ profile: true }),
    new MiniCssExtractPlugin({
      filename: 'static/css/[name].[hash:8].css',
      chunkFilename: 'static/css/[name].chunk.[hash:8].css',
    }),
    new StylelintPlugin({
      context: 'src',
      configFile: path.resolve(__dirname, '.stylelintrc'),
      files: '**/*.(css|less)',
      fix: true,
      emitError: true,
      emitWarning: true,
      failOnError: true,
      failOnWarning: true
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        API_HOST: JSON.stringify('http://127.0.0.1:8080'),
        LOGIN_URL: JSON.stringify('http://127.0.0.1:8080/oauth/login'),
        AUTH_SELF_URL: JSON.stringify('/v1/account/users/self')
      }
    })
  ],
};

if (production) {
  config.plugins.push(
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        API_HOST: JSON.stringify('https://zhique.xuzhao.xin'),
        LOGIN_URL: JSON.stringify('https://zhique.xuzhao.xin/oauth/login'),
        AUTH_SELF_URL: JSON.stringify('/v1/account/users/self')
      }
    })
  );
} else {
  config.devServer = {
    port: 8000,
    compress: true,
    historyApiFallback: true,
    hot: true
  };
  config.plugins.push(
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        API_HOST: JSON.stringify('http://127.0.0.1:8080'),
        LOGIN_URL: JSON.stringify('http://127.0.0.1:8080/oauth/login'),
        AUTH_SELF_URL: JSON.stringify('/v1/account/users/self')
      }
    })
  );
}

module.exports = config;
